export default class Magnifier {
    //ori为原图，large为放大区，fil为滤镜，choose为选择图片区
    constructor(ori, large, fil, choose) {
        if (choose) {
            //切换选择的图片
            choose.onclick = function (e) {
                //获取事件对象
                var e = e || window.event,
                    target = e.target || e.srcElement;
                //将原图和放大区的图片地址换为选择的图片地址
                ori.children[0].setAttribute("src", target.getAttribute("src"));
                large.children[0].setAttribute("src", target.getAttribute("src"))
            }
        }

        //绑定滤镜和放大区显示函数
        ori.onmouseover = function (e) {
            fil.style.display = "block";
            large.style.display = "block";
            fnImgMove()
        }

        //绑定滤镜消失函数
        ori.onmouseout = function () {
            fil.style.display = "none";
            large.style.display = "none";
        }

        //绑定鼠标移动事件
        ori.onmousemove = fnImgMove

        // 获取元素到最外层body的距离
        function offset(dom) {
            var bdl = dom.clientLeft
            var bdt = dom.clientTop
            var left = 0
            var top = 0
            while (dom) {
                left += dom.offsetLeft
                top += dom.offsetTop
                dom = dom.offsetParent
            }
            return {
                top: top - bdt,
                left: left - bdl
            }
        }

        //放大区图片移动函数
        function fnImgMove(e) {
            //获取事件对象
            var e = e || window.event;
            //获取鼠标距离页面的X，Y位置
            var mousePageX = e.pageX,
                mousePageY = e.pageY;
            var orip = offset(ori) 
            //滤镜的偏移距离
            var filLeft = mousePageX - orip.left - (ori.offsetWidth / 4),
                filTop = mousePageY - orip.top - (ori.offsetHeight / 4);
            //滤镜的移动范围
            if (filLeft > 0 && filLeft <= ori.offsetWidth / 2) {
                fil.style.left = filLeft + "px";
                //关联放大区的图片
                large.children[0].style.left = -2 * filLeft + "px";
            } else if (filLeft <= 0) {
                fil.style.left = 0 + "px"
                large.children[0].style.left = 0 + "px"
            } else {
                fil.style.left = ori.offsetWidth / 2 + "px"
                large.children[0].style.left = -2 * ori.offsetWidth / 2 + "px"
            }
            if (filTop > 0 && filTop < ori.offsetHeight / 2) {
                fil.style.top = filTop + "px"
                //关联放大区的图片
                large.children[0].style.top = -2 * filTop + "px";
            } else if (filTop <= 0) {
                fil.style.top = 0 + "px"
                large.children[0].style.top = 0 + "px"
            } else {
                fil.style.top = ori.offsetHeight / 2 + "px"
                large.children[0].style.top = -2 * ori.offsetHeight / 2 + "px"
            }
        }
    }

    //公共函数



}